package com.feilo.main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.poi.sl.usermodel.AutoShape;
import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

public class Test {
	public static void main(String[] args) throws IOException {
		/**
		Calendar cale = Calendar.getInstance();
		int year = cale.get(Calendar.YEAR);
		int month = cale.get(Calendar.MONTH);// 月份从0开始

		// 导入待拼接的.pptx文件
		InputStream is1 = new FileInputStream(new File("D:\\temp\\in\\1.pptx"));
		InputStream is2 = new FileInputStream(new File("D:\\temp\\in\\2.pptx"));
		InputStream is3 = new FileInputStream(new File("D:\\temp\\in\\3.pptx"));

		InputStream is4 = new FileInputStream(new File("D:\\temp\\out\\4.pptx"));

		XMLSlideShow ppt1 = new XMLSlideShow(is1);// 待拼接PPT1
		XMLSlideShow ppt2 = new XMLSlideShow(is2);// 待拼接PPT2
		XMLSlideShow ppt3 = new XMLSlideShow(is3);// 待拼接PPT3

		XMLSlideShow ppt4 = new XMLSlideShow(is4);// 待PPT4
		// XMLSlideShow headppt = getPPT(); // 此方法返回待拼接PPT3

		// 将PPT3依次插入到PPT2的末尾，createSlide()是在末尾创建
		// for (XSLFSlide srcSlide : headppt.getSlides()) {
		// datappt.createSlide().importContent(srcSlide);
		// }
		// 下面代码 是将当前月份的数值所对应ppt中的第几张 插入到PPT2的末尾
		List<XSLFSlide> list1 = ppt1.getSlides();
		List<XSLFSlide> list2 = ppt2.getSlides();
		List<XSLFSlide> list3 = ppt3.getSlides();

		ppt4.createSlide().importContent(list1.get(1));
		ppt4.createSlide().importContent(list2.get(4));
		ppt4.createSlide().importContent(list3.get(3));

		// ppt4.setSlideOrder(ppt4.getSlides().get(2), 0);
		// ppt4.setSlideOrder(ppt4.getSlides().get(1), 1);
		// ppt4.setSlideOrder(ppt4.getSlides().get(6), 2);

		// 以下为导出PPT的操作
		String filePath = "D:\\temp\\out\\";
		filePath = filePath.replace("\\", "\\\\");

		File dir = new File(filePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String path = dir.getPath();
		path = path.replace("\\", "\\\\");

		FileOutputStream out = new FileOutputStream(path + "\\4.pptx");
		ppt4.write(out);
		out.close();
		System.out.println("success");
		*/
		//Test.doPPT2007toImage("D:\\temp\\out\\4.pptx", "D:\\temp\\out\\");
		Test.doPPT2007toImage(new File("D:\\temp\\out\\4.pptx"));
		System.out.println("OK");
	}

	public static XMLSlideShow getPPT() throws IOException {
		// 导入要修改的PPT
		InputStream is = new FileInputStream(new File("D:\\temp\\in\\3.pptx"));
		XMLSlideShow ppt = new XMLSlideShow(is);
		List<XSLFSlide> Slides = ppt.getSlides();
		for (XSLFSlide slide : Slides) {
			List<XSLFShape> shapes = slide.getShapes();
			for (XSLFShape shape : shapes) {
				if (shape != null) {
					if (shape instanceof AutoShape) {
						try {
							if (((AutoShape) shape).getText().contains("{ye}")) {
								// 替换文字内容.用TextRun获取替换的文本来设置样式

								TextRun rt = ((AutoShape) shape)
										.setText(((AutoShape) shape).getText().replace("{ye}", "2018"));

								rt.setFontColor(Color.red);
								rt.setFontSize(13.5);
								rt.setFontFamily("微软雅黑");

							} else if (((AutoShape) shape).getText().contains("{mo}")) {
								((AutoShape) shape).setText(((AutoShape) shape).getText().replace("{mo}", "7"));
							}
							// System.out.println(((AutoShape)shape).getText());
						} catch (Exception ex) {

							ex.printStackTrace();
						}
						// }else {
						// System.out.println("Process me: " +
						// shape.getClass());
					}
				}
			}
		}
		return ppt;
	}

	public static boolean doPPT2007toImage(File file) {
		FileInputStream is = null;
		XMLSlideShow pptx = null ;
		try {
			is = new FileInputStream(file);
			pptx = new XMLSlideShow(is);
			is.close();
	
		    Dimension pgsize = pptx.getPageSize();
	
		    int idx = 1;
		    for (XSLFSlide slide : pptx.getSlides()) {
		    	//List<XSLFShape> shapes = slide.getShapes();
		    	
		        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
		        Graphics2D graphics = img.createGraphics();
		        // clear the drawing area
		        graphics.setPaint(Color.white);
		        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
	
		        // render
		        slide.draw(graphics);
		        
		        // save the output
		        FileOutputStream out = new FileOutputStream("D:\\temp\\out\\slide-" + idx + ".png");
		        javax.imageio.ImageIO.write(img, "png", out);
		        out.close();
	
		        idx++;
		    }
		}catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
	/**
	 * ppt2007文档的转换 后缀为.pptx
	 * 
	 * @param pptFile
	 *            PPT文件
	 * @param imgFile
	 *            图片将要保存的路径目录（不是文件）
	 * @param list
	 *            存放文件名的 list
	 * @return
	 */
	public static boolean doPPT2007toImage(String pptFile, String imgPath) {
		FileInputStream is = null;
		try {
			is = new FileInputStream(new File(pptFile));
			XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
			is.close();
			// 获取大小
			Dimension pgsize = xmlSlideShow.getPageSize();
			// 获取幻灯片
			List<XSLFSlide> slides = xmlSlideShow.getSlides();
			for (int i = 0; i < slides.size(); i++) {
				// 解决乱码问题
				List<XSLFShape> shapes = slides.get(i).getShapes();
				for (XSLFShape shape : shapes) {
					if (shape instanceof XSLFTextShape) {
						XSLFTextShape sh = (XSLFTextShape) shape;
						List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
						for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
							List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
							for (XSLFTextRun xslfTextRun : textRuns) {
								xslfTextRun.setFontFamily("宋体");
							}
						}
					}
				}
				// 根据幻灯片大小生成图片
				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
				Graphics2D graphics = img.createGraphics();
				graphics.setPaint(Color.white);
				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
				// 最核心的代码
				slides.get(i).draw(graphics);
				// 图片将要存放的路径
				File imaFile = new File(imgPath);
				String absolutePath = imaFile.getAbsolutePath() + "/" + (i + 1) + ".jpeg";
				File jpegFile = new File(absolutePath);
				// 图片路径存放
				// list.add((i + 1) + ".jpeg");
				// 如果图片存在，则不再生成
				if (jpegFile.exists()) {
					continue;
				}
				// 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
				FileOutputStream out = new FileOutputStream(jpegFile);
				// 写入到图片中去
				ImageIO.write(img, "jpeg", out);
				out.close();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
